package counter.com.baomidou.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import counter.com.baomidou.entity.Loudongbuginfo;
import counter.com.baomidou.entity.Loudongscaninfo;
import counter.com.baomidou.entity.Loudongtargetinfo;
import counter.com.baomidou.service.ILoudongbuginfoService;
import counter.com.baomidou.service.ILoudongscaninfoService;
import counter.com.baomidou.service.ILoudongtargetinfoService;
import counter.com.common.Result;
import counter.com.configuration.LoudongConfiguration;
import counter.com.connproperty.loudongjiance.*;
import counter.com.myservice.PollingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-10-07
 */
@RestController
@RequestMapping("/loudongbuginfo")
public class LoudongbuginfoController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    LoudongConfiguration configuration;

    @Autowired
    ILoudongbuginfoService buginfoService;

    @Autowired
    ILoudongtargetinfoService targetService;

    @Autowired
    ILoudongscaninfoService scanService;

    public static int STATUS_OPEN = 1;
    public static int STATUS_FIXED = 2;
    public static int STATUS_IGNORED = 3;
    public static int STATUS_MISSREPORT = 4;

    public static int LEVEL_IGNORE = 0;
    public static int LEVEL_LOW = 1;
    public static int LEVEL_MEDIUM = 2;
    public static int LEVEL_HIGH = 3;

    @PostMapping("/search")
    public Result search(@RequestBody BugSearchProperty data) {
        LambdaQueryWrapper<Loudongbuginfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Loudongbuginfo::getId);
        Page<Loudongbuginfo> page = new Page<>(data.getPage(), data.getPagesize());
        IPage<Loudongbuginfo> iPage = buginfoService.page(page, wrapper);
        List<Loudongbuginfo> records = iPage.getRecords();
        List<BugSearchRespBag> list = convertRecordsToProperty(records);
        return Result.success(new BugSearchRespProperty(iPage.getTotal(), list));
    }


    private List<BugSearchRespBag> convertRecordsToProperty(List<Loudongbuginfo> records) {
        List<BugSearchRespBag> list = new LinkedList<>();
        for (Loudongbuginfo info :
                records) {
            BugSearchRespBag property = new BugSearchRespBag();
            Integer targetId = info.getTid();
            Loudongtargetinfo target = targetService.getById(targetId);
            if (target == null) {
                //如果bug所属的目标对象已经消失，那么删除该bug
                buginfoService.removeById(info.getId());
                continue;
            }
            LambdaQueryWrapper<Loudongscaninfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Loudongscaninfo::getTid, targetId);
            property.setUrl(target.getUrl());
            property.setId(info.getId());
            property.setLevel(info.getLevel());
            property.setParam(info.getParam());
            property.setStatus(info.getStatus());
            property.setName(info.getName());
            property.setTime(info.getCreatedtime());
            property.setType(info.getType());
            list.add(property);
        }
        return list;
    }

    @PostMapping("/detail")
    public Result detail(@RequestBody BugDetailProperty data) {
        Loudongbuginfo bug = buginfoService.getById(data.getId());
        if (bug == null) {
            return Result.fail("没有找到合适的信息");
        }
        return Result.success(bug);
    }

    @PostMapping("/change")
    public Result change(@RequestBody BugChangeProperty data) {
        Integer[] ids = data.getIds();
        Integer status = data.getStatus();
        if (!checkStatus(status)) {
            return Result.fail("给定的参数status不合法");
        }
        for (int i = 0; i < ids.length; i++) {
            Loudongbuginfo bug = buginfoService.getById(ids[i]);
            if (bug == null) {
                continue;
            }
            bug.setStatus(status);
            if (!buginfoService.updateById(bug)) {
                return Result.fail("改变状态失败");
            }
        }
        return Result.success("改变状态成功");
    }

    private boolean checkStatus(Integer status) {
        if (status >= STATUS_OPEN && status <= STATUS_MISSREPORT) {
            return true;
        } else {
            return false;
        }
    }

    @PostMapping("/statistics")
    public Result statistics() {
        LambdaQueryWrapper<Loudongbuginfo> wrapper = new LambdaQueryWrapper<>();
        int totalCount = buginfoService.count();
        wrapper.eq(Loudongbuginfo::getLevel, LEVEL_LOW);
        int lowCount = buginfoService.count(wrapper);
        wrapper.clear();
        wrapper.eq(Loudongbuginfo::getLevel, LEVEL_MEDIUM);
        int mediumCount = buginfoService.count(wrapper);
        wrapper.clear();
        wrapper.eq(Loudongbuginfo::getLevel, LEVEL_HIGH);
        int highCount = 0;
//        if (ipPower()) {
        highCount = buginfoService.count(wrapper);
//        }
        BugStatisticsProperty property = new BugStatisticsProperty();
        property.setTotalCount(totalCount);
        property.setLowCount(lowCount);
        property.setMediumCount(mediumCount);
        property.setHighCount(highCount);
        return Result.success(property);
    }

    @PostMapping("/rank")
    public Result rank() {
        List<BugRankProperty> propertyList = new LinkedList<>();
        LambdaQueryWrapper<Loudongbuginfo> wrapper = new LambdaQueryWrapper<>();


        for (int i = 0; i < PollingService.bugNames.length; i++) {
            wrapper.eq(Loudongbuginfo::getType, i);
//            if (!ipPower()) {
//                wrapper.lt(Loudongbuginfo::getLevel, LEVEL_HIGH);
//            }
            int count = buginfoService.count(wrapper);
            List<Loudongbuginfo> list = buginfoService.list(wrapper);
            if (list.size() > 0) {
                BugRankProperty property = new BugRankProperty(list.get(0).getName(), i, count);
                propertyList.add(property);
            }
            wrapper.clear();
        }
        Collections.sort(propertyList);
        return Result.success(propertyList);
    }
}
